package com.common.Interceptor;

import com.common.exception.RRException;
import com.common.utils.JWTUtil;
import com.modules.user.entity.UserEntity;
import com.modules.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object object) throws Exception {
        //从请求头内获取token
        // token没有问题则返回true
        String token = request.getHeader("token");
        if (token == null){
            throw new RRException("登录已失效，请重新登录", 401);
        }else {
            UserEntity userEntity = userService.getUserByLoginToken(token);
            if (userEntity == null){
                //token不存在
                throw new RRException("登录已失效，请重新登录" , 401);
            }else {
                //token信息存在则判断过期
                if (!token.equals(userEntity.getToken())){
                    throw new RRException("登录已失效，请重新登录", 401);
                }
            }
        }
        return true;
    }

}
